package com.level2app.ui.welcome.view;

import android.graphics.BitmapFactory;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;


import com.level2app.base.BaseViewModel;
import com.level2app.bean.CheckReferralCodeBean;
import com.level2app.di.retrofit.BaseNetCallback;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;

/**
 * Created by S
 * time 2024/8/12
 */
public class ScanQRViewModel extends BaseViewModel {
    public MutableLiveData<String> mStringData = new MutableLiveData<>();
    public void parsImage(String path) {
        addSubscribe(Observable.<String>create(emitter -> {
                    try {
                        String s = QRCodeDecoder.syncDecodeQRCode(BitmapFactory.decodeFile(path));
                        emitter.onNext(s);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String s) {
                        mStringData.setValue(s);
                    }

                    @Override
                    public void onError(Throwable e) {
//                        ToastHelper.showShort(R.string.barcode_not_recognized_yet);
                    }

                    @Override
                    public void onComplete() {

                    }
                }));
    }

    public MutableLiveData<CheckReferralCodeBean> checkReferralCodeData = new MutableLiveData<>();

    public void checkReferralCode() {
        Map<String, Object> map = new HashMap<>();
        map.put("referral_code", mStringData.getValue());
        addSubscribe(mRetrofitHelper.checkReferralCode(map).subscribeWith(new BaseNetCallback<CheckReferralCodeBean>(){

            @Override
            public void onSuccess(CheckReferralCodeBean baseModel) {
                checkReferralCodeData.setValue(baseModel);
            }

            @Override
            public void onError(String message) {
                super.onError(message);
                mErrorData.setValue(message);
            }
        }));
    }
}